package com.cc.bsp.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

public class HomePageFilter implements Filter {

	private String action;

	public void init(FilterConfig filterConfig) throws ServletException {

		action = "home.action";

		String x = filterConfig.getInitParameter("home");

		if (StringUtils.isNotBlank(x)) {
			action = x;
		}

	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		HttpServletRequest httpServletRequest = (HttpServletRequest) request;

		HttpServletResponse httpServletResponse = (HttpServletResponse) response;

		String contextPath = httpServletRequest.getContextPath();

		String requestURI = httpServletRequest.getRequestURI();

		if (contextPath.equalsIgnoreCase(requestURI) || (contextPath + "/").equalsIgnoreCase(requestURI)) {
			String url = "";
			if (action.startsWith("/")) {
				url = contextPath + action;
			} else {
				url = contextPath + "/" + action;
			}
			httpServletResponse.sendRedirect(url);
		} else {
			chain.doFilter(request, response);
		}

	}

	public void destroy() {
		action = null;
	}

	public String getAction() {
		return action;
	}

	public void setAction(String action) {
		this.action = action;
	}

}
